#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

void Usage(std::string proc)
{
    std::cerr << "Usage:\n\t" << proc << "serverip serverport" << std::endl;
}
int main(int argc, char *argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        return 1;        
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0)
    {
        std::cerr << "sock create error" << std::endl;
        return 2;
    }

    // 构建目标主机信息
    struct sockaddr_in peer;
    memset(&peer, 0, sizeof(peer));
    peer.sin_family = AF_INET;
    peer.sin_port = htons(serverport);
    peer.sin_addr.s_addr = inet_addr(serverip.c_str());

    int n = ::connect(sockfd, (struct sockaddr*)&peer, sizeof(peer));
    if(n < 0)
    {
        std::cerr << "connect error" << std::endl;
        return 3;
    }

    while(true)
    {
        std::cout << "Please Enter# ";
        std::string outstring;
        std::getline(std::cin, outstring);

        ssize_t s = send(sockfd, outstring.c_str(), outstring.size(), 0);
        if(s > 0)
        {
            char inbuffer[1024];
            int n = recv(sockfd, inbuffer, sizeof(inbuffer) - 1, 0);
            if(n > 0)
            {
                inbuffer[n] = 0;
                std::cout << inbuffer << std::endl;
            }
            else
            {
                break;
            }
        }
        else
        {
            break;
        }
    }

    ::close(sockfd);

    return 0;
}